//
//  VersionManager.swift
//  MobileRTCSwiftSample
//
//  Created by zhangheng on 2019/6/11.
//  Copyright © 2019 Zoom Video Communications, Inc. All rights reserved.
//


struct VersionInfo {
    var url: String             //下载应用URL
    var title: String           //title
    var message: String         //提示内容
    var must_update: Bool       //是否强制更新
    var version: String         //版本
}

class VersionManager: NSObject {
    
    //本地版本
    static func localVersion() -> String? {
        return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    }
    
    //
    static func versionUpdate(msg:String?,version:String?,url:String?=nil) {
        //1 请求服务端数据，并进行解析,得到需要的数据
        //2 版本更新
        let defaultmsg = "⭐️⭐️修复已知的BUG."//"提示更新内容，解决了xxx等一系列问题，新增了xxx等功能！\n提示更新内容，解决了xxx等一系列问题\n新增了xxx等功能！"//
        let defaultVersion = "3.5"
        let newmsg = (msg == nil || msg == "")  ? defaultmsg:msg
        let newversion = version == nil ? defaultVersion:version
        let upUrl = url == nil ? mt_url_appstore:url!
        handleUpdate(VersionInfo(url: upUrl , title: "有新版本啦".localized(), message: newmsg!, must_update: false, version: newversion!))
    }
    
    /// 版本更新
    private static func handleUpdate(_ info: VersionInfo) {
        guard let localVersion = localVersion()else { return }
        if isIgnoreCurrentVersionUpdate(info.version) { return }
        if self.versionCompare(localVersion: localVersion, serverVersion: info.version) {
            let alert = NSAlert.init()
            alert.messageText = "发现新版本的 \(info.version)，当前版本 \(AppInfo.majorVersion())，是否立即下载更新？"
            alert.addButton(withTitle: "下载更新")
            alert.addButton(withTitle: "取消")
            let respose = alert.runModal()
            if respose == NSApplication.ModalResponse.alertFirstButtonReturn {
                //UpdateEngine.shared.loadying(url: nil)
                let window = NSWindow.init(contentViewController: URAlertViewConroller.init(urlString: nil))
                window.lorderFront(nil)
            }
        }
    }
    
    // 版本比较
    private static func versionCompare(localVersion: String, serverVersion: String) -> Bool {
        let result = localVersion.compare(serverVersion, options: .numeric, range: nil, locale: nil)
        if result == .orderedDescending || result == .orderedSame{
            return false
        }
        return true
    }
    
    // 是否忽略当前版本更新
    private static func isIgnoreCurrentVersionUpdate(_ version: String) -> Bool {
        return false//UserDefaults.standard.string(forKey: "IgnoreCurrentVersionUpdate") == version
    }
}


